﻿/**
 * io绑定方法
 *
 * @param {socket.io} io socket.io实例
 */


module.exports = function (io, userCache) {
    io.sockets.on('connection', function (socket) {
        var socketid = socket.id;

        var users = userCache.users;
        console.log("a user connected, socketid:" + socketid);

        //当前用户加入
        socket.on('user join', function (userId) {
            userCache.addUser(userId, socket);
        });

        //当前用户切换tab页时,需要更新替换掉原来的socket
        socket.on('user focus', function (userId) {
            userCache.changeUser(userId, socket);
        });

        //与 服务器 断开
        socket.on('disconnect', function () {
            userCache.removeUser(socket.id);
        });

        //通用的方法
        var fnList = ['queryMessage', 'sendMessage', 'updateMessageReadStatus', 'deleteMessage'];

        for (var i = 0; i < fnList.length; i++) {
            let fnName = fnList[i];

            socket.on(fnName, function (data, fn) {
                fn(data);
                socket.broadcast.emit('receiveMessage', data);                
            });
        }
    });
}